package com.sugeun.stopwatch;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.mail.Quota.Resource;
import javax.mail.internet.NewsAddress;

import com.android.mail.Email;
import com.android.mail.NetworkUitl;
import com.sugeun.stopwatch.R;

import com.mocoplex.adlib.AdlibActivity;
import com.mocoplex.adlib.AdlibConfig;
import com.mocoplex.adlib.AdlibManager.AdlibVersionCheckingListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;

import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.ToneGenerator;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.SystemClock;
import android.util.Log;

import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.ads.AdRequest;
import com.google.ads.AdView;


public class StopWatchMain extends AdlibActivity implements OnClickListener
{
	private static final String TAG = "StopWatch";
	private static final int DEFAULT_BUTTON_STATE = 0;
	private static final int START_BUTTON_STATE = 1;
	private static final int STOP_BUTTON_STATE = 2;
	
	private static final int LAPCOUNT = 199;
	private static final String STOPWATCHSTARTED = "stopwatchstarted";
	private static final String STARTTIME = "starttime";
	private static final String ENDTIME = "endtime";
	
	/*private static final String ANI_LEFT = "ani_left";
	private static final String ANI_RIGHT = "ani_right";
	private static final String ANI_TOP = "ani_top";
	private static final String ANI_BOTTOM = "ani_bottom";
	private static final String ANI_BACK = "ani_back";
	
	private static final String ANI_DEFAULT_LEFT = "ani_default_left";
	private static final String ANI_DEFAULT_RIGHT = "ani_default_right";
	private static final String ANI_DEFAULT_TOP = "ani_default_top";
	private static final String ANI_DEFAULT_BOTTOM = "ani_default_bottom";
	private static final String ANI_DEFAULT_BACK = "ani_back";*/
    
	private static final String VOLUME_UP = "volume_up";
	private static final String VOLUME_DOWN = "volme_down";
	
//	private static String FRAME_GETRIGHT = "frame_getright";
	
	private TextView mHourTextView;
	private TextView mMinuteTextView;
	private TextView mSecondTextView;
	private TextView mCentiSecondTextView;
	private TextView mCentiSecondTextView2;
	
	private ListView sw_listview;
	private Button sw_start_btn;
	private Button sw_stop_btn;
	private Button sw_lap_btn;
	private Button sw_reset_btn;
	private Button sw_resume_btn;
	private Timer mTimer;

	private long time;
	private String mHourStr;
	private String mMinuteStr;
	private String mSecondStr;
	private String mCentiSecondStr;
	private String mCentiSecondStr2;
	
	private int lap_count;
	
	private long mStartTime = 0;
	private long mFlowTime = 0;
	
	private boolean bStartTimer = false;
	
	private List<StopWatch> lap_list;
	private StopWatchAdapter swAdapter;
	
    private PowerManager mPm;
    private WakeLock mWakeLock;

	private static SharedPreferences mSharedPreferences;
	private static SharedPreferences.Editor mEditor;
	
	private IntentFilter mIntentFilter;
	
	private boolean isClickable = true;
	private boolean isStart = false;//volume down key laptime
	private boolean isClickStart = true;//volume up key startbutton
	private boolean isDownKey = true;
	
	/*private  int default_getleft;
	private  int default_getRight;
	private  int default_getTop;
	private  int default_getBottom;
	
	   private ImageView img1;
	   private AnimationDrawable mAni;*/
//	   private AdView adView;
	  /* private int img_getLeft;
	   private int img_getRight;*/
	  
	   
	 /*  private FrameLayout fl;
	   private int fl_left;
	   private int fl_right;*/
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		Log.d(TAG, "[onCreate]");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stopwatch_main);
		
		initAds();
        
        // 실제 광고 호출이 될 adview 를 연결합니다. 
        this.setAdsContainer(R.id.ads);
        
		init();
		if (time == 0L){
			clearList();
		}
	}
	
	@Override
	protected void onResume() 
	{
		// TODO Auto-generated method stub
		super.onResume();
		
		Log.d(TAG, "[onResume]");
		NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
     	nm.cancel(1);

     	
		lap_list.clear();
		if(!isClickable){
		    sw_lap_btn.setClickable(true);
		    isClickable = true;
		}
		restore_lab_list();
		int isStopWatchStarted = loadIsStopWatchStartedPreferences();

		
		if (START_BUTTON_STATE == isStopWatchStarted) {
			Long time = loadStartTimePreferences();
			stopTimer();
			startTimer(time);
			setButtonState(START_BUTTON_STATE);
		
			
		}
		else if(STOP_BUTTON_STATE == isStopWatchStarted)
		{
			Long time = loadStopTimePreferences();					
			
			
			Log.d(TAG, "time : "+time);
			mFlowTime = time;
			
			
            mHourStr = getTwoLengthNum(((time/1000)/60)/60);
			mMinuteStr = getTwoLengthNum((time/60000)%60);
			mSecondStr = getTwoLengthNum((time/1000)%60);
		
			mCentiSecondStr = Long.toString((time/100)%10);
			mCentiSecondStr2 = Long.toString((time/10)%10);		
			
			
			mHourTextView.setText(mHourStr);
			mMinuteTextView.setText(mMinuteStr);
			mSecondTextView.setText(mSecondStr);
			mCentiSecondTextView.setText(mCentiSecondStr);
			mCentiSecondTextView2.setText(mCentiSecondStr2);
			setButtonState(STOP_BUTTON_STATE);
		}
		else if (DEFAULT_BUTTON_STATE == isStopWatchStarted) 
		{

			stopTimer();
			clearList();				
			setButtonState(DEFAULT_BUTTON_STATE);
		}
	}

	@Override
	protected void onPause()
	{
		super.onPause();
		Log.d(TAG, "[onPause]");
		if (mWakeLock.isHeld()) 
		{
			mWakeLock.release();
		}
		if(isClickable){
            sw_lap_btn.setClickable(false);
            isClickable = false;
        }
		save_lab_list();
	}

	@Override
	protected void onStop() 
	{
		super.onStop();
		Log.d(TAG, "[onStop]");
		
		stopTimer();
		
	}

	private void save_lab_list() {
		String count;
		String time1;
		String time2;
		for (int i = 0; i < lap_list.size(); i++) {
			Log.d(TAG, "LAPLISTSIZE  : " + lap_list.size());
			StopWatch lv = lap_list.get(i);
			count = lv.getLap_count();
			time1 = lv.getLap_time1();
			time2 = lv.getLap_time2();
			mEditor.remove(count);
			mEditor.remove(time1);
			mEditor.remove(time2);
			
			mEditor.putString("lap_count" + i, count);		
			mEditor.putString("lap_time1" + i, time1);			
			mEditor.putString("lap_time2" + i, time2);			
		}
		mEditor.putInt("lap_num", lap_list.size());	
		mEditor.commit();
	}

	private void restore_lab_list() {
		int lap_num = mSharedPreferences.getInt("lap_num", 0);
		if (lap_num != 0) {
			for (int i = lap_num; i > 0; --i) {
				
				String count = Integer.toString(lap_num + 1 - i);
				String time1 = mSharedPreferences.getString("lap_time1"
						+ (i - 1), "");
				String time2 = mSharedPreferences.getString("lap_time2"
						+ (i - 1), "");
				lap_list.add(0, new StopWatch(count, time1, time2));
			}
			swAdapter.notifyDataSetChanged();
		}
		if (lap_num == 100) {
			sw_lap_btn.setEnabled(false);
		}
	}

	@Override
	protected void onDestroy() 
	{
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.d(TAG, "[onDestroy]");

		if(mBroadCastReceiver != null)
		{
			unregisterReceiver(mBroadCastReceiver);
			mBroadCastReceiver = null;
		}	
	}

	private void init()
	{
		Log.d(TAG, "[init] : initialize");
		Typeface face = Typeface.createFromAsset(getAssets(),
        "fonts/DS-DIGIT.TTF");
        mPm = (PowerManager)getSystemService(POWER_SERVICE);
        mWakeLock = mPm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "dim_Wake");

        mSharedPreferences = getSharedPreferences("stopwatch_sugeun", 0);
		mEditor = mSharedPreferences.edit();
        
		mIntentFilter = new IntentFilter();
//		mIntentFilter.addAction("android.intent.action.TIME_SET");
		mIntentFilter.addAction("android.intent.action.SCREEN_OFF");
		registerReceiver(mBroadCastReceiver, mIntentFilter);
//		
		mHourTextView = (TextView)findViewById(R.id.sw1_textview);
		mMinuteTextView = (TextView)findViewById(R.id.sw2_textview);
		mSecondTextView = (TextView)findViewById(R.id.sw3_textview);
		mCentiSecondTextView = (TextView)findViewById(R.id.sw4_textview);
		mCentiSecondTextView2 = (TextView)findViewById(R.id.sw5_textview);
		
		mHourTextView.setTypeface(face);
		mMinuteTextView.setTypeface(face);
		mSecondTextView.setTypeface(face);
		mCentiSecondTextView.setTypeface(face);
		mCentiSecondTextView2.setTypeface(face);

		

		
//		adView = (AdView)this.findViewById(R.id.adView);
//        adView.loadAd(new AdRequest());
		
		/*fl = (FrameLayout)findViewById(R.id.fl);
		img1 = (ImageView)findViewById(R.id.img1);
		mAni = (AnimationDrawable)img1.getBackground();*/
		//home, back key 클릭시 초기값
//		fl_right = loadFrameGetRight();
		isStart = isVolume_down();
		isClickStart = isVolume_up();
		
		/*default_getleft = loadAni_default_Location_left();
		default_getRight = loadAni_default_Location_right();
		default_getTop = loadAni_default_Location_top();
		default_getBottom = loadAni_default_Location_bottom();*/
//		if(isAniBackkey()){
//			Log.e(TAG,"loadAniLocation_left : "+loadAniLocation_left()+", loadAniLocation_right : "+loadAniLocation_right());
//			img1.layout(loadAniLocation_left(), loadAniLocation_top(), loadAniLocation_right(), loadAniLocation_bottom());
//			saveAniBackkey(false);
//		}
		
		//Log.e(TAG,"default_getleft11 : "+default_getleft+", default_getRight : "+default_getRight);
		//
		//Log.d(TAG,"fl_right init : "+fl_right);
		sw_listview = (ListView)findViewById(R.id.sw_list);
		
		sw_start_btn = (Button)findViewById(R.id.sw_start_btn);
		sw_start_btn.setOnClickListener(this);
		sw_stop_btn = (Button)findViewById(R.id.sw_stop_btn);
		sw_stop_btn.setOnClickListener(this);
		sw_lap_btn = (Button)findViewById(R.id.sw_lap_btn);
		sw_lap_btn.setOnClickListener(this);
		sw_reset_btn = (Button)findViewById(R.id.sw_reset_btn);
		sw_reset_btn.setOnClickListener(this);
		sw_resume_btn = (Button)findViewById(R.id.sw_resume_btn);
		sw_resume_btn.setOnClickListener(this);
	
		lap_list = new ArrayList<StopWatch>();
		swAdapter = new StopWatchAdapter(this, R.layout.stopwatch_row, lap_list);
		sw_listview.setAdapter(swAdapter);
		
		
		
		initSound();
		}

	private void updateArray(){
		lap_list.clear();
		sw_listview.setAdapter(swAdapter);
	}
	private void startTimer(long startTime)
	{
		Log.d(TAG, "[startTimer] : start ");
		
		
		if(mWakeLock == null)
		{
			mWakeLock = mPm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "dim_Wake");
			mWakeLock.acquire();	
		}else{
			mWakeLock.acquire();
		}
		
		
		if (bStartTimer == true) {
			Log.e(TAG, "[startTimer] : already started");
			return;
		}
		bStartTimer = true;
		
		saveStartTimePreferences(startTime);
		mStartTime = startTime;
		mTimer = new Timer();
		mTimer.scheduleAtFixedRate(new TimerTask()
		{
			@Override
			public void run() 
			{
			
				time = ((SystemClock.elapsedRealtime()-mStartTime));				
				
				mHourStr = getTwoLengthNum(((time/1000)/60)/60);
				mMinuteStr = getTwoLengthNum((time/60000)%60);
				mSecondStr = getTwoLengthNum((time/1000)%60);
				mCentiSecondStr = Long.toString((time/100)%10);
				mCentiSecondStr2 = Long.toString((time/10)%10);		
				
				/*img_getLeft = 1;
				img_getRight = 1;*/
					
				if(time >= 359999990)
				{
					stopTimer();
					
					time = 359999990;
					mHourStr = getTwoLengthNum(((time/1000)/60)/60);
					mMinuteStr = getTwoLengthNum((time/60000)%60);
					mSecondStr = getTwoLengthNum((time/1000)%60);
					mCentiSecondStr = Long.toString((time/100)%10);
					mCentiSecondStr2 = Long.toString((time/10)%10);
					
				}
				
				else if(time < 0)
				{
					stopTimer();
					mHourStr = "00";
					mMinuteStr = "00";
					mSecondStr = "00";
					mCentiSecondStr = "0";
					mCentiSecondStr2 = "0";
					saveIsStopWatchStartedPreferences(DEFAULT_BUTTON_STATE);
					
					setDefault();
					if (mWakeLock != null) 
					{
						mWakeLock.release();
						mWakeLock = null;
					}
				}
				
				updateStopWatchView();
			}
		}, 0, 10);
	}
	
	private void setDefault()
	{
		Runnable runnable = new Runnable()
		{
			public void run() 
			{			
				clearList();
				setButtonState(DEFAULT_BUTTON_STATE);
			}
		};
		runOnUiThread(runnable);	
	}
	
	private void stopTimer()
	{
		Log.d(TAG, "[stopTimer] : stop ");
		
		if(mTimer != null)
		{
			mTimer.cancel();
		}
		bStartTimer = false;
	}
	
	private void updateStopWatchView()
	{
		Runnable runnable = new Runnable()
		{
			public void run() 
			{									
				mHourTextView.setText(mHourStr);
				mMinuteTextView.setText(mMinuteStr);
				mSecondTextView.setText(mSecondStr);
				mCentiSecondTextView.setText(mCentiSecondStr);
				mCentiSecondTextView2.setText(mCentiSecondStr2);
				/////////////////////////////////////////////////////////////
				//Log.e(TAG, "imgGetLeft : "+(img1.getLeft()));
				/*img1.layout(img1.getLeft()+img_getLeft, img1.getTop(), img1.getRight()+img_getRight, img1.getBottom());
				if(img1.getLeft()==fl_right){					
					img1.layout(default_getleft-default_getRight, default_getTop, default_getleft, default_getBottom);//진행시 이미지가 FrameLayout 맨끝에 닿았을때 처음이미지 위치보다 왼쪽으로 -start_right으로 이동
				}*/
				
			}
		};
		runOnUiThread(runnable);	
	}
//	private void updateStopAniView()
//	{
//		Runnable runnable = new Runnable()
//		{
//			public void run() 
//			{									
//				img1.layout(loadAniLocation_left(), loadAniLocation_top(), loadAniLocation_right(), loadAniLocation_bottom());
//	     		saveAniBackkey(false);
//			}
//		};
//		runOnUiThread(runnable);	
//	}
	
	private void addList()
	{
		swAdapter.notifyDataSetChanged();
		if(LAPCOUNT > lap_list.size())
		{
			Log.d(TAG, "[addList] : add the lap");
			lap_count++;
			
			StopWatch lv = new StopWatch(Integer.toString(lap_list.size()+1), mHourStr + ":" + mMinuteStr + ":" + mSecondStr, "."+mCentiSecondStr+""+mCentiSecondStr2);
			
			lap_list.add(0, lv);
			swAdapter.notifyDataSetChanged();
		}
		else if(LAPCOUNT == lap_list.size())
		{
			sw_lap_btn.setEnabled(false); 
			StopWatch lv = new StopWatch(Integer.toString(lap_list.size()+1), mHourStr + ":" + mMinuteStr + ":" + mSecondStr, "."+mCentiSecondStr+""+mCentiSecondStr2);	
			lap_list.add(0, lv);
			
			Log.d(TAG, "[addList] :  full");
//			AlertDialog.Builder list_full_dialog = new AlertDialog.Builder(this);
//			list_full_dialog.setTitle(R.string.stopwatch_listFull_title)
//							.setIcon(android.R.drawable.ic_dialog_alert)
//							.setMessage(R.string.STR_Clock_SWLISTFULLMESSAGE_NORMAL)
//							.setPositiveButton(R.string.timer_set_alerttone_ok, new DialogInterface.OnClickListener()
//							{
//								public void onClick(DialogInterface dialog,	int which) 
//								{
//									
//								}
//							})
//							.show();
			Toast.makeText(this, R.string.stopwatch_listFull_title, Toast.LENGTH_LONG).show();
			isStart = false;
		}
		sw_listview.requestFocus();
		sw_listview.setSelection(0);
	}
	
	private void clearList()
	{
		Log.d(TAG, "[clearList] : clear ");
		lap_count = 0;
		
		updateArray();
	}
	private int buttonstate;
	private void setButtonState(int btn_state)
	{
		switch(btn_state)
		{
			case DEFAULT_BUTTON_STATE :
			{
				buttonstate = DEFAULT_BUTTON_STATE;
				sw_reset_btn.setVisibility(View.GONE);
				sw_resume_btn.setVisibility(View.GONE);
				sw_stop_btn.setVisibility(View.GONE);
				sw_lap_btn.setVisibility(View.GONE);
				sw_start_btn.setVisibility(View.VISIBLE);
				sw_lap_btn.setEnabled(true); 
				break;
			}
			case START_BUTTON_STATE :
			{	
				buttonstate = START_BUTTON_STATE;
				sw_reset_btn.setVisibility(View.GONE);
				sw_resume_btn.setVisibility(View.GONE);
				sw_start_btn.setVisibility(View.GONE);
				sw_stop_btn.setVisibility(View.VISIBLE);
				sw_lap_btn.setVisibility(View.VISIBLE);
				break;
			}
			case STOP_BUTTON_STATE :
			{
				buttonstate = STOP_BUTTON_STATE;
				sw_start_btn.setVisibility(View.GONE);
				sw_stop_btn.setVisibility(View.GONE);
				sw_lap_btn.setVisibility(View.GONE);
				sw_reset_btn.setVisibility(View.VISIBLE);
				sw_resume_btn.setVisibility(View.VISIBLE);
				break;
			}
			default :
			    break;
		}
	}
	
	
	
	public void onClick(View v) 
	{	
		switch(v.getId())
		{	
			case R.id.sw_start_btn:
			{
				Log.d(TAG, "[onClick] : start button");
				
				/*default_getleft = img1.getLeft();
				default_getRight = img1.getRight();
				default_getTop = img1.getTop();
				default_getBottom = img1.getBottom();*/
	//			Log.e(TAG,"default_getleft1 : "+default_getleft+", default_getRight : "+default_getRight+", default_getTop : "+default_getTop+", default_getBottom : "+default_getBottom);
//				saveAni_default_Location(img1.getLeft(), img1.getTop(), img1.getRight(), img1.getBottom());
				/*mAni.start();
				fl_right = fl.getRight();
				saveFrameGetRight(fl_right);
				Log.d(TAG, "fl_right : "+fl_right);*/
				
				
				
				playSound(START_ALARM);
				startTimer(SystemClock.elapsedRealtime());
				
				saveIsStopWatchStartedPreferences(START_BUTTON_STATE);
				setButtonState(START_BUTTON_STATE);
				isStart = true;
				isClickStart = false;
				break;
			}
			case R.id.sw_stop_btn:
			{
				Log.d(TAG, "[onClick] : stop button");
//				mAni.stop();
				playSound(STOP_ALARM);
				mFlowTime = time;
				isStart = false;
				isClickStart = false;
				
				stopTimer();
				saveStopTimePreferences(time);
				saveIsStopWatchStartedPreferences(STOP_BUTTON_STATE);
				setButtonState(STOP_BUTTON_STATE);
				
				if (mWakeLock.isHeld()) 
				{
					mWakeLock.release();
				}
				break;
			}
			case R.id.sw_lap_btn:
			{
				Log.d(TAG, "[onClick] : lap button");
				isClickStart = false;
				playSound(LAP_ALARM);
				addList();
				break;
			}
			case R.id.sw_reset_btn:
			{
				Log.d(TAG, "[onClick] : reset button");
				
				//img1.layout(loadAni_default_Location_left(), loadAni_default_Location_top(), loadAni_default_Location_right(), loadAni_default_Location_bottom());
//				Log.e(TAG,"default_getleft : "+default_getleft+", default_getRight :"+default_getRight);
//				img1.layout(default_getleft, default_getTop, default_getRight, default_getBottom);
				playSound(REFLASH_ALARM);
				stopTimer();
				clearList();
				isStart = false;
				isClickStart = true;
				mHourTextView.setText(R.string.sw_defaultvalue2);
				mMinuteTextView.setText(R.string.sw_defaultvalue2);
				mSecondTextView.setText(R.string.sw_defaultvalue2);
				mCentiSecondTextView.setText(R.string.sw_defaultvalue);
				mCentiSecondTextView2.setText(R.string.sw_defaultvalue);
				saveIsStopWatchStartedPreferences(DEFAULT_BUTTON_STATE);
				
				
				setButtonState(DEFAULT_BUTTON_STATE);
				if (mWakeLock.isHeld()) 
				{
					mWakeLock.release();
				}
				break;
			}
			case R.id.sw_resume_btn:
			{
				Log.d(TAG, "[onClick] : resume button");
				playSound(RESUME_ALARM);
//				mAni.start();
				isStart = true;	
				isClickStart = false;
				startTimer(SystemClock.elapsedRealtime() - mFlowTime);
				
				saveIsStopWatchStartedPreferences(START_BUTTON_STATE);
				
				setButtonState(START_BUTTON_STATE);
				break;
			}
			default:
			{
				break;
			}
		}
	}

	
	private BroadcastReceiver mBroadCastReceiver = new BroadcastReceiver()
	{
		public void onReceive(Context context, Intent intent) 
		{
			if("android.intent.action.SCREEN_OFF".equals(intent.getAction()))
			{
				Log.e(TAG,"====POWER_KEY===");
			}

		}
	};
	
	
	
	private String getTwoLengthNum(long nValue)
	{
		String sResult = "";
		
		if(10 > nValue)
		{
			sResult = "0" + nValue;
		}
		else
		{
			sResult = "" + nValue;
		}
		
		return sResult;
	}
	
	
	
	
	private int tempID = -1; 
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean check = true;	
		//Log.e(TAG,"keyCode = "+keyCode+" //// event = "+event);
		switch(keyCode)	{
							
			case KeyEvent.KEYCODE_VOLUME_UP:  
				if(isClickStart){
				//	Log.e(TAG,"isClickStart ????= ");
					/*default_getleft = img1.getLeft();
					default_getRight = img1.getRight();
					default_getTop = img1.getTop();
					default_getBottom = img1.getBottom();*/
				//	Log.e(TAG,"default_getleft : "+default_getleft+", default_getRight : "+default_getRight+", default_getTop : "+default_getTop+", default_getBottom : "+default_getBottom);
					/*mAni.start();
					fl_right = fl.getRight();
					saveFrameGetRight(fl_right);*/
				//	Log.d(TAG, "fl_right : "+fl_right);
				startTimer(SystemClock.elapsedRealtime());
				saveIsStopWatchStartedPreferences(START_BUTTON_STATE);
				setButtonState(START_BUTTON_STATE);
				isStart = true;
				playSound(START_ALARM);
				}
				if(!isClickStart&&isStart){
					playSound(STOP_ALARM);
//					mAni.stop();
					mFlowTime = time;
					isStart = false;
					isClickStart = false;
					stopTimer();
					saveStopTimePreferences(time);
					saveIsStopWatchStartedPreferences(STOP_BUTTON_STATE);
					setButtonState(STOP_BUTTON_STATE);
					
					if (mWakeLock.isHeld()) 
					{
						mWakeLock.release();
					}
				}else if(!isClickStart&&!isStart){
					playSound(RESUME_ALARM);
//					mAni.start();
					isStart = true;	
					isClickStart = false;
					startTimer(SystemClock.elapsedRealtime() - mFlowTime);
					
					saveIsStopWatchStartedPreferences(START_BUTTON_STATE);
					
					setButtonState(START_BUTTON_STATE);
					
				}
				//tempID = 0;
				break;
				
			case KeyEvent.KEYCODE_VOLUME_DOWN:
				if(isDownKey&&isStart){
					addList();
					isDownKey = false;
					playSound(LAP_ALARM);
				}
				//tempID = 1; 
			break;
			
			case KeyEvent.KEYCODE_MENU:
				Log.e(TAG,"===KEYCODE_MENU===");
				check = false;
				break;
			case KeyEvent.KEYCODE_SEARCH:
				Log.e(TAG,"===KEYCODE_SEARCH===");
				check = false;
				break;			
			default:{
				check = false;
				Log.e(TAG,"===KEYCODE_BACKKEY===");
				
				
				
				if(isStart){//스탑워치 진행시
//					NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//				     	nm.cancel(1);
//				   		Notification noti = new Notification(R.drawable.icon, getText(R.string.app_name).toString(), System.currentTimeMillis());
//				   		noti.flags |= Notification.FLAG_AUTO_CANCEL;
//				   		Intent intent = new Intent(StopWatch.this, com.sugeun.tab.TabManager.class);
//				   		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//				   		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
//				   		noti.setLatestEventInfo(this, getText(R.string.app_name).toString(), getText(R.string.start).toString(), contentIntent);
//				   		nm.notify(1, noti);
				   	   
				   		
				   		
					
//				}else{//스탑워치 정지시
//					saveAniBackkey(true);//
//					Log.d(TAG, "img1.getLeft : "+img1.getLeft()+", img1.getRight : "+img1.getRight());
//					saveAniLocation(img1.getLeft(), img1.getTop(), img1.getRight(), img1.getBottom());
				}
				 saveVolumeKey(isClickStart, isStart);
//				saveAni_default_Location(default_getleft, default_getTop, default_getRight, default_getBottom);
				if (mWakeLock.isHeld()) 
				{
					mWakeLock.release();
				}
			}
		}
		if(check){		

			//playSound(tempID);
			//tempID = -1;
			
			return true;
		}
		
		return super.onKeyDown(keyCode, event);
	}	
	
	//click home key
	@Override
	protected void onUserLeaveHint() {
		// TODO Auto-generated method stub
		super.onUserLeaveHint();
		Log.e(TAG,"===KEYCODE_HOMEKEY===");
		   
		
		   NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
	       	nm.cancel(1);
	   		Notification noti = new Notification(R.drawable.icon, getText(R.string.app_name).toString(), System.currentTimeMillis());
	   		noti.flags |= Notification.FLAG_AUTO_CANCEL;
	   		Intent intent = new Intent(StopWatchMain.this, StopWatchMain.class);
	   		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	   		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
	   		noti.setLatestEventInfo(this, getText(R.string.app_name).toString(), getText(R.string.start).toString(), contentIntent);
	   		nm.notify(1, noti);
	   		saveVolumeKey(isClickStart, isStart);
//	   		saveAni_default_Location(default_getleft, default_getTop, default_getRight, default_getBottom);
	   		
			if (mWakeLock.isHeld()) 
			{
				mWakeLock.release();
			}

	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		boolean check = true;
		//Log.e(TAG,"keyCode = "+keyCode+" //// event = "+event);
		switch(keyCode)
		{
			
			case KeyEvent.KEYCODE_VOLUME_UP:  {
				tempID = 0; 
				isClickStart = false;
				break;}
			case KeyEvent.KEYCODE_VOLUME_DOWN:{
				tempID = 1;
				isDownKey = true;
				break;
				}
				
			
			default:{
				check = false;
			}
		}
		if(check){	
			stopSound(tempID);
			tempID = -1;
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}



	//sound settings
	private SoundPool sound_pool; 
	private final static int START_ALARM = 0;
	private final static int LAP_ALARM = 1;
	private final static int STOP_ALARM = 2;
	private final static int REFLASH_ALARM = 3;
	private final static int RESUME_ALARM = 4;
	private int start_alarm;
	private int lap_alarm;
	private int stop_alarm;
	private int reflash_alarm;
	private int resume_alarm;

	private void initSound(){ 
	sound_pool = new SoundPool( 5, AudioManager.STREAM_ALARM, 0 );
//	sound_pool = new SoundPool( 5, AudioManager.STREAM_MUSIC, 0 );
	start_alarm = sound_pool.load(this, R.raw.bang3, 1);	//start
	lap_alarm = sound_pool.load(this, R.raw.continuous_shot, 2);//lap
	stop_alarm = sound_pool.load(this, R.raw.cam_snap_0, 2);//stop
	reflash_alarm = sound_pool.load(this, R.raw.chongqiang, 1);//reset
	resume_alarm = sound_pool.load(this, R.raw.resume, 2);//reset

	} 
 

	public void playSound(int id){ 
		switch(id){
		case START_ALARM :
			if(isClickStart){
			sound_pool.play( start_alarm, 1f, 1f, 0, 0, 1f );
			}
			break;
		
		case LAP_ALARM :
			if(isStart){
			sound_pool.play( lap_alarm, 1f, 1f, 0, 0, 1f );			
			}
			break;
		case STOP_ALARM :			
				sound_pool.play( stop_alarm, 1f, 1f, 0, 0, 1f );
			break;	
		case REFLASH_ALARM :			
			sound_pool.play( reflash_alarm, 1f, 1f, 0, 0, 1f );
			break;	
		case RESUME_ALARM :			
			sound_pool.play( resume_alarm, 1f, 1f, 0, 0, 1f );
			break;	
		}	
	}
	
	public void stopSound(int id){ 
		sound_pool.stop(id);
	}
	private final static int MENU_OP_SEND = 1;
	private EditText message = null;
	private EditText user_mail = null;
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		  getMenuInflater().inflate(R.menu.stopwatch_list_menu, menu);
		//menu.add(0, MENU_OP_SEND, 0, R.string.send_developer);
		 return super.onCreateOptionsMenu(menu);
		//return true;
	}
	
	
	
	private boolean send_mail = true;
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch(item.getItemId()){
			//타이머로 이동			
//		case R.id.menu_item_timer :
//			  startActivity(new Intent(this, com.sugeun.timer.TimerActivity.class));
//			return true;
			// 메일 보내기	
		case R.id.menu_item_mail:
				int network = NetworkUitl.checkStatus(StopWatchMain.this);
				if(network == NetworkUitl.NETWORK_NONE){
					Toast.makeText(StopWatchMain.this, R.string.not_connected_network, Toast.LENGTH_LONG).show();
					return false;
				}
				
				LayoutInflater inflater = (LayoutInflater)getSystemService(this.LAYOUT_INFLATER_SERVICE);
				View view = inflater.inflate(R.layout.send_mail, null);
				AlertDialog.Builder build = new AlertDialog.Builder(this);
				build.setTitle(R.string.send_developer);
				build.setView(view);
				message = (EditText)view.findViewById(R.id.message);				
				user_mail = (EditText)view.findViewById(R.id.user_mail);				
				
				
				build.setPositiveButton(R.string.send_bt, new DialogInterface.OnClickListener() {
					
					
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						
						final ProgressDialog pDialog = new ProgressDialog(StopWatchMain.this);
						pDialog.setTitle(R.string.send_dialog_title);
						pDialog.setMessage(getText(R.string.current_send_mail).toString());
						pDialog.show();
						if(!yokCheck(message.getText().toString())){										
//							Toast.makeText(StopWatch.this, "욕설문구 혹은 내용을 입력하지 않았습니다. 확인후 다시 보내세요", Toast.LENGTH_SHORT).show();
							
							pDialog.dismiss();
						}else{							
							new Thread(new Runnable() {
								
								
								public void run() {
									// TODO Auto-generated method stub
									Email sendMail = new Email("hwangsugeun@gmail.com", "dksEmf1380");								
									
									try {
										sendMail.sendMail(getText(R.string.stopwatch_user).toString(), (message.getText().toString()+"\n======  "+user_mail.getText()+"  ====="), 
												"hwangsugeun@gmail.com", getText(R.string.message_receiver).toString());
									} catch (Exception e) {
										// TODO Auto-generated catch block
										Log.e(TAG,"e===="+e);
									
										 Message msg = mHandler.obtainMessage();
										 msg.what = 0;
										 mHandler.sendMessage(msg);
										
									}
									pDialog.dismiss();
									if(send_mail){
										Message msg = mHandler.obtainMessage();
										 msg.what = 1;
										 mHandler.sendMessage(msg);
									}
								}
							}).start();
						}
					}
				});
				build.setNegativeButton(android.R.string.cancel, null);
				build.create().show();
				 return true;
		case R.id.menu_item_sound : 
//			  startActivity(new Intent(this, com.sugeun.timer.TimeZoneSettings.class));
			  startActivity(new Intent(this, SoundSettings.class));
			  return true;
		}
//		return true;
		  return super.onOptionsItemSelected(item);
}
	
                     

		Handler mHandler = new Handler(){
			 
	    	public void handleMessage(Message msg){
	   		  	switch (msg.what) {			
					
				case 0:
					Toast.makeText(StopWatchMain.this, R.string.fail_send_mail, Toast.LENGTH_LONG).show();
					send_mail = false;
					break;
					
				case 1 : 
					Toast.makeText(StopWatchMain.this, R.string.success_send_mail, Toast.LENGTH_LONG).show();					
					break;
				default:
					break;
				}
	 
	    	};
	 
	 };

   private String [] hangleYok = {"시발","씨발","새끼","개시키","개새키","개샤키","개새끼","개자식","미친","미친놈","병신","멍청이","씹","놈","자식","짜식","씨바","시바","씹아","씹알","또라이","도라이"};
   private boolean yokCheck(String text){
	   Log.e(TAG, "text : "+text);
	  
	    for(int i=0; i<hangleYok.length;i++){
	    	if(text.contains(hangleYok[i])){	
	    		Log.e(TAG,"hangleYok[i] : "+hangleYok[i]);
	    		Toast.makeText(StopWatchMain.this, getText(R.string.yock).toString(), Toast.LENGTH_SHORT).show();
	    		return false;
	    	}
	    }
	    if(text.equals("")){
	    	Toast.makeText(StopWatchMain.this, getText(R.string.empty_mail).toString(), Toast.LENGTH_SHORT).show();
			   return false;
		   }
	   return true;
   }



   public static void saveIsStopWatchStartedPreferences(int stopwatchstate)
	{
		mEditor.putInt(STOPWATCHSTARTED, stopwatchstate);
		mEditor.commit();
	}
	
	public static int loadIsStopWatchStartedPreferences()
	{
		return mSharedPreferences.getInt(STOPWATCHSTARTED, -1);
	}
	
	public static void saveStartTimePreferences(Long starttime)
	{
		mEditor.putLong(STARTTIME, starttime);
		mEditor.commit();
	}
	
	public static Long loadStartTimePreferences()
	{
		return mSharedPreferences.getLong(STARTTIME, 0);
	}
	
	public static void saveStopTimePreferences(Long stoptime)
	{
		mEditor.putLong(ENDTIME, stoptime);
		mEditor.commit();
	}
	
	public static Long loadStopTimePreferences()
	{
		return mSharedPreferences.getLong(ENDTIME, 0);
	}

	/*public static void saveAniLocation(int left, int top, int right, int bottom)
	{
		mEditor.putInt(ANI_LEFT, left);
		mEditor.putInt(ANI_TOP, top);
		mEditor.putInt(ANI_RIGHT, right);
		mEditor.putInt(ANI_BOTTOM, bottom);
		mEditor.commit();
	}*/

	/*public static int loadAniLocation_left()
	{
		return mSharedPreferences.getInt(ANI_LEFT, 0);
	}
	public static int loadAniLocation_right()
	{
		return mSharedPreferences.getInt(ANI_RIGHT, 0);
	}
	public static int loadAniLocation_top()
	{
		return mSharedPreferences.getInt(ANI_TOP, 0);
	}
	public static int loadAniLocation_bottom()
	{
		return mSharedPreferences.getInt(ANI_BOTTOM, 0);
	}
	
	public static void saveAni_default_Location(int left, int top, int right, int bottom)
	{
		mEditor.putInt(ANI_DEFAULT_LEFT, left);
		mEditor.putInt(ANI_DEFAULT_TOP, top);
		mEditor.putInt(ANI_DEFAULT_RIGHT, right);
		mEditor.putInt(ANI_DEFAULT_BOTTOM, bottom);
		mEditor.commit();
	}*/
	
	/*public static int loadAni_default_Location_left()
	{
		return mSharedPreferences.getInt(ANI_DEFAULT_LEFT, 0);
	}
	public static int loadAni_default_Location_right()
	{
		return mSharedPreferences.getInt(ANI_DEFAULT_RIGHT, 0);
	}
	public static int loadAni_default_Location_top()
	{
		return mSharedPreferences.getInt(ANI_DEFAULT_TOP, 0);
	}
	public static int loadAni_default_Location_bottom()
	{
		return mSharedPreferences.getInt(ANI_DEFAULT_BOTTOM, 0);
	}*/
	
	/*public static void saveAniBackkey(boolean back)
	{
		mEditor.putBoolean(ANI_BACK, back);
		mEditor.commit();
	}
	public static boolean isAniBackkey()
	{
		return mSharedPreferences.getBoolean(ANI_BACK, false);
	}*/
	
	public static void saveVolumeKey(boolean up, boolean down)
	{
		mEditor.putBoolean(VOLUME_UP, up);
		mEditor.putBoolean(VOLUME_DOWN, down);
		mEditor.commit();
	}
	
	public static boolean isVolume_up()
	{
		return mSharedPreferences.getBoolean(VOLUME_UP, true);
	}
	public static boolean isVolume_down()
	{
		return mSharedPreferences.getBoolean(VOLUME_DOWN, false);
	}
	/*public static int loadFrameGetRight()
	{
		return mSharedPreferences.getInt(FRAME_GETRIGHT, 0);
	}
	
	public static void saveFrameGetRight(int getRight)
	{
		mEditor.putInt(FRAME_GETRIGHT, getRight);
		mEditor.commit();
	}*/
	
	protected void initAds()
    {
    	// 광고 스케줄링 설정을 위해 아래 내용을 프로그램 실행시 한번만 실행합니다. (처음 실행되는 activity에서 한번만 호출해주세요.)
    	
        // 광고 subview 의 패키지 경로를 설정합니다. (실제로 작성된 패키지 경로로 수정해주세요.)
    	// 쓰지 않을 광고플랫폼은 삭제해주세요.
//	    AdlibConfig.getInstance().bindPlatform("TAD","com.sugeun.advertisement.SubAdlibAdViewTAD");
        AdlibConfig.getInstance().bindPlatform("ADAM","com.sugeun.advertisement.SubAdlibAdViewAdam");
        AdlibConfig.getInstance().bindPlatform("ADMOB","com.sugeun.advertisement.SubAdlibAdViewAdmob");
//        AdlibConfig.getInstance().bindPlatform("ADCUBE","test.adlib.project.ads.SubAdlibAdViewAdcube");
        
//        AdlibConfig.getInstance().bindPlatform("CAULY","test.adlib.project.ads.SubAdlibAdViewCauly");
        
        // 쓰지 않을 플랫폼은 JAR 파일 및 test.adlib.project.ads 경로에서 삭제하면 최종 바이너리 크기를 줄일 수 있습니다.
        
        // adlib 에서 발급받은 api 키를 입력합니다.
        // http://adlib.mocoplex.com/m/media.aspx
        AdlibConfig.getInstance().setAdlibKey("4f9543670cf291e5cd76c8da",true);
                
        // 광고 타겟팅을 위한 사용자 정보를 입력합니다. (옵션)
        // gender(M/F/0), age(10/20/30/40/0), lat(위도), lon(경도)
//        AdlibConfig.getInstance().setAdInfo("0", "20", "31.111", "127.111");
                
    }
	
}
